<template>
    <!-- 客户信息输入 -->
    <div class="draw-main">
      <div class="h-main">
        <div class="h-form" style='margin-top:-20px'>
            <div class="h-label"><span class="h-spacing">姓名</span></div>
            <el-input v-model='cardInfo.name' class='h-input'  placeholder="输入姓名"/>
            <div class="h-label" style="margin-top:15px;"><span class="h-spacing">身份证号</span></div>
            <el-input v-model='cardInfo.idcard' class='h-input' @blur='idcardBlur' placeholder="输入身份证号"/>
            <!-- <div class="flex-row">
              <div style="padding:0 5px;">
                <div class="h-label" style="margin-top:15px;"><span class="h-spacing">年龄</span> AGE</div>
                <el-input v-model='cardInfo.age' class='h-input' />
              </div>
              <div style="padding:0 5px;">
                <div class="h-label" style="margin-top:15px;"><span class="h-spacing">性别</span> GENDER</div>
                <el-select v-model="cardInfo.sex" placeholder="性别" :popper-append-to-body="false">
                  <el-option label="男" value="男"></el-option>
                  <el-option label="女" value="女"></el-option>
                </el-select>
              </div>
            </div> -->
            <div class="h-label" style="margin-top:15px;"><span class="h-spacing">联系方式</span></div>
            <el-input v-model='cardInfo.phone' class='h-input' maxlength="11" placeholder="输入联系方式"/>
            <div class="h-label" style="margin-top:15px;"><span class="h-spacing">有无癌症史</span></div>
            <el-select v-model="cardInfo.isCancer" placeholder="选择有无癌症史" :popper-append-to-body="false" style="width: 100%;">
              <el-option label="无" value="无"></el-option>
              <el-option label="有" value="有"></el-option>
            </el-select>
            <div class="h-label" style="margin-top:15px;"><span class="h-spacing">卡号</span></div>
            <el-input v-model='cardInfo.cardNum' class='h-input' placeholder="输入卡号" @blur='getInfoByCard'/>
            <div class="h-label" style="margin-top:15px;"><span class="h-spacing">激活码</span></div>
            <el-input v-model='cardInfo.cardPwd' class='h-input' placeholder="输入激活码"/>
            <div style="text-align: left;padding-top: 5px;">
              <el-checkbox v-model="checked">
                <span style="color: #fff;">我已阅读并同意<el-link target="_blank" :href="'/#/agree?term='+curCardInfo.term" type="primary">《精准医疗权益用户须知》</el-link></span>
              </el-checkbox>
            </div>
            <div style="height: 20px;"></div>
          <el-button type="primary" class="card-button-border1" size="medium" @click='toQuery'>立即激活</el-button>
        </div>
        <!-- <div class="userNotice" @click="show=true">用户告知
          <span v-if="isAgree != 0" style="color:red;"> 【{{isAgree == 1 ? '同意' : '不同意'}}】</span>
        </div> -->
        <!-- <div class="card-button-border" @click='toQuery'>立即激活</div> -->
      </div>
      <van-dialog v-model="show" title="用户告知" show-cancel-button @confirm="handleBtn(1)"
      @cancel="handleBtn(2)"
      confirm-button-text="同意" cancel-button-text="不同意" confirm-button-color="#5812a9">
        <img src="../../assets/h5/userSaid.jpg" class='noticeImg'/>
      </van-dialog>
    </div>
  </template>
  
  <script>
    import cardApi from '@/api/h5/card'
    export default {
      data() {
        return {
          checked:false,
          show: false,
          cardInfo:{
            name:'',
            idcard:'',
            age:'',
            sex:'',
            phone:'',
            isCancer:'',
            cardNum:'',
            cardPwd:'',
            birthday:''
          },
          isAgree: 0,
          activeInfo:'',
          curCardInfo:''
        };
      },
      created(){
        document.title = '激活卡';
        this.getInfo()
      },
      methods: {
        getInfo(){
          this.activeInfo = JSON.parse(localStorage.getItem("activeInfo"));
        },
        // 失去焦点
        idcardBlur(){
          if(!this.IsCard(this.cardInfo.idcard)){
            this.$toast("请输入正确的身份证号");
            return false;
          }
          this.cardInfo.age = this.$utils.getAgeByIdCard(this.cardInfo.idcard);
        },
        getInfoByCard(){
          cardApi.getCardInfoByCardNum({cardNum:this.cardInfo.cardNum}).then(res => {
            this.curCardInfo = res.data;
          })
        },
        // 激活
        toQuery(){
          if(this.cardInfo.name == ''){
            return this.$toast("请输入姓名");
          }
          if(!this.IsCard(this.cardInfo.idcard)){
            return this.$toast("请输入正确的身份证号");
          }
          if(!this.isAgeBetween28And65(this.cardInfo.idcard)){
            this.$dialog.alert({
              title: '提示',
              message: '年龄必须在满28天并且不超过65岁之间',
            }).then(() => {
              // on close
            });
            return false;
          }
          if(this.cardInfo.phone == ''){
            return this.$toast("请输入联系方式");
          }
          if(this.cardInfo.isCancer == ''){
            return this.$toast("请选择有无癌症史");
          } 
          if(this.cardInfo.cardNum == ''){
            return this.$toast("请输入卡号");
          } 
          if(this.cardInfo.cardPwd == ''){
            return this.$toast("请输入激活码");
          } 
          if(!this.checked){
            return this.$alert("请详细阅读并同意《精准医疗权益用户须知》");
          }
          var cardsInfo = this.getInfoFromId(this.cardInfo.idcard);
          console.log(cardsInfo)
          console.log(this.cardInfo,'cardInfo')
          this.cardInfo.age =cardsInfo.age;
          this.cardInfo.birthday =cardsInfo.birthday;
          this.cardInfo.sex =cardsInfo.sex;
          this.$toast.loading({
              message: '激活中...',
              forbidClick: true,
              loadingType: 'spinner',
          });
          cardApi.addCustomer(this.cardInfo).then(res => {
            this.$toast.clear();
            if(res.status == 200){
              localStorage.setItem("activeInfo",JSON.stringify(res.data));
              this.$router.push('activationSuccess')
            }
          })
        },
        isAgeBetween28And65(idCardNumber) {
          // 身份证号码第7到14位是出生年月日
          const birthYear = parseInt(idCardNumber.substr(6, 4), 10);
          const birthMonth = parseInt(idCardNumber.substr(10, 2), 10) - 1; // JavaScript中月份是从0开始的
          const birthDay = parseInt(idCardNumber.substr(12, 2), 10);

          // 创建出生日期对象
          const birthDate = new Date(birthYear, birthMonth, birthDay);

          // 获取当前日期
          const today = new Date();

          // 计算年龄差
          let ageDiffMs = today.getTime() - birthDate.getTime();
          console.log(ageDiffMs,'ageDiffMs')
          const ageDateDiff = new Date(ageDiffMs);
          const ageYears = ageDateDiff.getFullYear() - 1; // 减去1是因为还没有过生日
          const ageMonths = ageDateDiff.getMonth();
          // 计算年龄
          let age = today.getFullYear() - birthDate.getFullYear();

          // 计算是否满足28天
          const twentyEightDays = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 28);
          if (birthDate > twentyEightDays) {
              return false; // 如果出生日期在28天之前，那么年龄不足28天
          }
          // 判断是否在65岁及以下
          return age <= 65;
        },
        handleBtn(isAgree){
          this.isAgree = isAgree;
        },
        IsCard(str) {
          var reg =  /(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/;
          return reg.test(str);
        },
        getInfoFromId(idNumber) {
          if (idNumber.length !== 18) {
            throw new Error('Invalid ID number length');
          }
          const birthday = idNumber.substring(6, 14);
          const sex  = idNumber[16] % 2 === 0 ? '女' : '男';
          const today = new Date();
          const age = today.getFullYear() - idNumber.substring(6, 10) - ((today.getMonth() + 1 >= 3) ? 0 : 1);
        
          return {
            age,
            sex,
            birthday: `${birthday.substring(0, 4)}-${birthday.substring(4, 6)}-${birthday.substring(6, 8)}`
          };
        },
      },
    }
</script>
<style scoped>
.draw-main{
    justify-content: center;
    height: 100%;
} 
.h-main>>>.el-input-group__append{
  font-size:15px;
  color: #5812a9 !important;
}
.h-main>>>.flex-row{
  display: flex;
  justify-content: space-between;
}
.h-form>>>.el-input--small .el-input__inner{
  height: 42px;
  line-height: 42px;
  margin-top:15px;
  border-radius: 10px;
  background: #f1d7fc;
  font-size: 15px;
  color: #5812a9 !important;
}
.h-form>>>.el-select .el-input .el-select__caret{
  color: #5812a9 !important;
  margin-top: 5px;
}
.h-form>>>.el-popper{
  background: #f1d7fc;
  color: #4d168b !important;
}
.h-form>>>.el-select-dropdown__item.hover, .h-form>>>.el-select-dropdown__item:hover{
  background: #f1d7fc;
  color: #5812a9 !important;
}
.userNotice{
  text-align: center;
  color:#f1d7fc;
  font-size:18px;
  margin-top:-20px;
}
.noticeImg{
  width: 100%;margin-top:10px;
}
.card-button-border{
  margin: 22% auto !important;
}
.card-button-border1{
  background: #dac9ec;
  color: #5711a7;
  width: 100%;
  border: none;
  margin-top: 20px 0;
}
</style>